<?php

namespace tmcore\services\wechat;

use app\common\enum\ChannelEnum;
use app\common\model\user\User;
use app\common\service\UserService;
use tmcore\exceptions\WeChatException;
use app\common\model\user\UserAuthLog;

/**
 * 微信开放平台用户类
 */
class WxOpUserService
{
    protected UserAuthLog $userAuthModel;

    protected array $user = [];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->userAuthModel = (new UserAuthLog);
    }

    /**
     * 获取微信用户信息
     * @param array $where
     * @param string $field
     * @return array
     */
    public function getWxUserInfo(array $where, $field = '*')
    {
        return $this->userAuthModel->where($where)->where(['channel' => ChannelEnum::PC])->field($field)->findOrEmpty()->toArray();
    }

    /**
     * 根据uid获取openid
     * @param int $uid
     * @return mixed
     */
    public function uidToOpenid(int $uid)
    {
        return $this->userAuthModel->where(['uid' => $uid])->where(['channel' => ChannelEnum::PC])->value('openid');
    }

    /**
     * 用户授权登录
     * @param $params
     * @return array
     * @throws WeChatException
     */
    public function authUserLogin($params)
    {
        if(empty($params['openid'])) throw new WeChatException('openid不可为空');
        if ($this->checkUserAuth($params)) {
            return $this->updateUser($params);
        } else {
            return $this->addUser($params);
        }
    }

    /**
     * 检查用户授权
     * @param $params
     * @return array|bool
     * @throws WeChatException
     */
    public function checkUserAuth($params) {

        // 授权记录检验
        $auth = UserAuthLog::where(['openid' => $params['openid']])->field('id,uid,openid,unionid')->findOrEmpty()->toArray();

        if(!$auth && (!empty($params['unionid']))) {
            $auth = UserAuthLog::where(['unionid' => $params['unionid']])->field('id,uid,openid,unionid')->findOrEmpty()->toArray();
        }

        // 手机号唯一用户检验
        if(!empty($params['mobile'])) {
            $auth['uid'] = User::where(['mobile' => $params['mobile']])->value('id');
        }

        if(!$auth) return false;

        $user = User::where(['id' => $auth['uid']])->field('id,avatar,nickname,user_token,mobile,status')->findOrEmpty()->toArray();
        if($user['status'] == 0) throw new WeChatException('您的账号已被禁用，请联系客服');
        $this->user = $user;

        return $user;
    }


    /**
     * 更新微信粉丝信息
     * @param $params
     * @return array
     */
    public function updateUser($params)
    {
        // 检验用户授权记录
        (new UserService)->userAuth($this->user['id'], ChannelEnum::PC, $params['openid'], $params['unionid']??'');

        //更新登录信息
        User::where(['id' => $this->user['id']])->update(['last_time' => time(), 'last_ip' => request()->ip()]);

        return [
            'uid' => $this->user['id'],
            'openid' => $params['openid'],
            'unionid' => $params['unionid'] ?? '',
        ];
    }

    /**
     * 新增用户
     * @param $params
     * @return array
     * @throws WeChatException
     */
    public function addUser($params) {

        try {
            $userService = (new UserService);

            // 新用户注册
            $res = $userService->register([
                'account' => 'wx_op_' . com_random(10,'0123456789'),
                'password' => '123456',
                'channel' => ChannelEnum::PC,
                'openid' => $params['openid']
            ]);

            if(empty($res['id'])) throw new WeChatException('新增用户失败');

            $uid = $res['id'];

            // 检验用户授权记录
            $userService->userAuth($uid, ChannelEnum::PC, $params['openid'], $params['unionid'] ?? '');

            return [
                'uid' => $uid,
                'openid' => $params['openid'],
                'unionid' => $params['unionid'] ?? ''
            ];

        } catch (\Exception $e) {
            throw new WeChatException($e->getMessage());
        }
    }
}